package com.hiwan.unions.util;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.AssetManager;
import android.content.res.Resources;
import android.os.Bundle;
import android.os.Environment;
import android.support.design.widget.TabLayout;
import android.text.TextUtils;
import android.util.TypedValue;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.webkit.ValueCallback;
import android.widget.LinearLayout;

import com.hiwan.unions.activity.webView.WebViewDetailedActivity;
import com.hiwan.unions.activity.webView.WebViewNoTitleActivity;
import com.hiwan.unions.application.ConstantsValues;
import com.hiwan.unions.view.ProgressWebView;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.File;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;

/**
 * 配置文件
 */
public class Utils {
    private final static String ALBUM_PATH = Environment.getExternalStorageDirectory() + File.separator + "hipay" + File.separator;
    private String titles;
    private Context contexts;

    // 过滤特殊字符
    public static String StringFilter(String str) throws PatternSyntaxException {
        // 清除掉所有特殊字符
        String regEx = "[`~!@#$%^&*()+=|{}':;',\\[\\].<>/?~！@#￥%……& ;*（）——+|{}【】‘；：”“’。，、？-]";
        Pattern p = Pattern.compile(regEx);
        Matcher m = p.matcher(str);
        return m.replaceAll("").trim();
    }

    public static String getExtensionName() {
        String tile = String.valueOf((int) ((Math.random() * 9 + 1) * 10000000)) + String.valueOf(((int) ((Math.random() * 9 + 1) * 100000000)));
        return tile;
    }

    /**
     * 生成随机数命名
     */
    public static String getExtensionName(int length) {
        String retStr = "";
        String strTable = "1234567890";
        int len = strTable.length();
        boolean bDone = true;
        do {
            retStr = "";
            int count = 0;
            for (int i = 0; i < length; i++) {
                double dblR = Math.random() * len;
                int intR = (int) Math.floor(dblR);
                char c = strTable.charAt(intR);
                if (('0' <= c) && (c <= '9')) {
                    count++;
                }
                retStr += strTable.charAt(intR);
            }
            if (count >= 2) {
                bDone = false;
            }
        } while (bDone);

        return retStr;
    }

    public static String Urls(String url, SharedPreferences userInfoC, SharedPreferences userInfo) {
        if (CheckUtils.containsString(url, "?")) {
            return url + "&authtoken=" + AESKit.decodebase64AndDecrypt(userInfo.getString(ConstantsValues.AUTHTOKEN, ""), ConstantsValues.ASEKIPASSWORD) + "&city=" + userInfoC.getString(ConstantsValues.CITYNAME, "成都市") + "&area_code=" + userInfoC.getString(ConstantsValues.CITYNAMECODE, "510100") + "&integral=" + userInfoC.getString(ConstantsValues.points, "0") + "&t=" + System.currentTimeMillis();
        } else {
            return url + "?authtoken=" + AESKit.decodebase64AndDecrypt(userInfo.getString(ConstantsValues.AUTHTOKEN, ""), ConstantsValues.ASEKIPASSWORD) + "&city=" + userInfoC.getString(ConstantsValues.CITYNAME, "成都市") + "&area_code=" + userInfoC.getString(ConstantsValues.CITYNAMECODE, "510100") + "&integral=" + userInfoC.getString(ConstantsValues.points, "0") + "&t=" + System.currentTimeMillis();
        }
    }

    public static String Urls2(String url, SharedPreferences userInfoC, SharedPreferences userInfo) {
        if (CheckUtils.containsString(url, "?")) {
            return url + "&authtoken=" + AESKit.decodebase64AndDecrypt(userInfo.getString(ConstantsValues.AUTHTOKEN, ""), ConstantsValues.ASEKIPASSWORD) + "&city=" + userInfoC.getString(ConstantsValues.CITYNAMEOne, "成都市") + "&area_code=" + userInfoC.getString(ConstantsValues.CITYNAMEOneCode, "510100") + "&integral=" + userInfoC.getString(ConstantsValues.points, "0") + "&t=" + System.currentTimeMillis();
        } else {
            return url + "?authtoken=" + AESKit.decodebase64AndDecrypt(userInfo.getString(ConstantsValues.AUTHTOKEN, ""), ConstantsValues.ASEKIPASSWORD) + "&city=" + userInfoC.getString(ConstantsValues.CITYNAMEOne, "成都市") + "&area_code=" + userInfoC.getString(ConstantsValues.CITYNAMEOneCode, "510100") + "&integral=" + userInfoC.getString(ConstantsValues.points, "0") + "&t=" + System.currentTimeMillis();

        }
    }

    /**
     * 过滤换行符和空格
     *
     * @param str
     * @return
     */
    public static String blankString(String str) {
        String dest = "";
        if (str != null) {
            Pattern p = Pattern.compile("\\s*|\t|\r|\n");
            Matcher m = p.matcher(str);
            dest = m.replaceAll("");
        }
        return dest;
    }

    /**
     * 计算图片的缩放值
     */
    public static String date(String date, Date d1, SimpleDateFormat df, SimpleDateFormat cc) {
        try {
            Date d2 = df.parse(date);//传进的时间
            long cha = d2.getTime() - d1.getTime();
            int day = new Long(cha / (1000 * 60 * 60 * 24)).intValue();
            if (day == 0) {
                return "今天";
            } else if (day == -1) {
                return "昨天";
            } else {
                return DateStringe(date, df, cc);
            }
        } catch (ParseException e) {
            e.printStackTrace();
            return date;
        }
    }

    /**
     * 年月
     *
     * @return
     */
    public static String DateStringe(String date, SimpleDateFormat df, SimpleDateFormat cc) {
        try {
            Date strDate = df.parse(date);
            date = cc.format(strDate);
        } catch (Exception ex) {
            System.out.println(ex.getMessage());
        }
        return date;
    }

    /**
     * 年月id
     *
     * @return
     */
    public static int DateId(String date, SimpleDateFormat df, SimpleDateFormat cc) {
        try {
            Date strDate = df.parse(date);
            date = cc.format(strDate);
            if (date.equals("")) {
                return 0;
            }
        } catch (Exception ex) {
            System.out.println(ex.getMessage());
        }
        return Integer.parseInt(date);
    }

    public static boolean setMeizuStatusBarDarkIcon(Activity activity, boolean dark) {
        boolean result = false;
        if (activity != null) {
            try {
                WindowManager.LayoutParams lp = activity.getWindow().getAttributes();
                Field darkFlag = WindowManager.LayoutParams.class
                        .getDeclaredField("MEIZU_FLAG_DARK_STATUS_BAR_ICON");
                Field meizuFlags = WindowManager.LayoutParams.class
                        .getDeclaredField("meizuFlags");
                darkFlag.setAccessible(true);
                meizuFlags.setAccessible(true);
                int bit = darkFlag.getInt(null);
                int value = meizuFlags.getInt(lp);
                if (dark) {
                    value |= bit;
                } else {
                    value &= ~bit;
                }
                meizuFlags.setInt(lp, value);
                activity.getWindow().setAttributes(lp);
                result = true;
            } catch (Exception e) {
            }
        }
        return result;
    }

    /**
     * 从asset路径下读取对应文件转String输出
     */
    public static String getJson(Context mContext, String fileName) {
        String content = "";
        AssetManager am = mContext.getAssets();
        try {
            InputStream is = am.open(fileName);
            content = readTextFromSDcard(is) + "";
        } catch (Exception e) {
            e.printStackTrace();
            return "";
        }

        return content;
    }

    /**
     * 按行读取txt
     *
     * @param is
     * @return
     * @throws Exception
     */
    private static String readTextFromSDcard(InputStream is) throws Exception {
        InputStreamReader reader = new InputStreamReader(is, "UTF-8");
        BufferedReader bufferedReader = new BufferedReader(reader);
        StringBuffer buffer = new StringBuffer("");
        String str;
        while ((str = bufferedReader.readLine()) != null) {
            buffer.append(str);
            buffer.append("\n");
        }

        return buffer.toString();
    }

    public static boolean setMiuiStatusBarDarkMode(Activity activity, boolean darkmode) {
        Class<? extends Window> clazz = activity.getWindow().getClass();
        try {
            int darkModeFlag = 0;
            Class<?> layoutParams = Class.forName("android.view.MiuiWindowManager$LayoutParams");
            Field field = layoutParams.getField("EXTRA_FLAG_STATUS_BAR_DARK_MODE");
            darkModeFlag = field.getInt(layoutParams);
            Method extraFlagField = clazz.getMethod("setExtraFlags", int.class, int.class);
            extraFlagField.invoke(activity.getWindow(), darkmode ? darkModeFlag : 0, darkModeFlag);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    public static String callXw(JSONObject jsonObject, String titles) {
        return "<!DOCTYPE html>" +
                "<html lang=\"zh-CN\">" +
                "<head>" +
                "<meta charset=\"UTF-8\">" +
                "<meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge,chrome=1\"/>" +
                "<meta name=\"format-detection\" content=\"telephone=no\">" +
                "<meta name=\"msapplication-tap-highlight\" content=\"no\">" +
                "<meta name=\"viewport\"" +
                "content=\"user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width\">" +
                "<title>" + titles + "</title>" +
                "<link rel=\"stylesheet\" href=\"file:///android_asset/zixun.min.css\">" +
                "</head>" +
                "<body style=\"padding: 5px; background-color:#fff\">" +
                "<div class=\"container\">" +
                "<div class=\"art-box\">" +
                "<p class=\"title\">" + JsonUtil.getString(jsonObject, "title") + "</p>" +
                "<p class=\"date\"><span>日期：</span><span>" + JsonUtil.getString(jsonObject, "publish_time") + "</span></p>" +
                "<div class=\"art-text-box\">" + JsonUtil.getString(jsonObject, "content") +
                "</div>" +
                "</div>" +
                "</div>" +
                "</body>" +
                "</html>";
    }

    public static String callGanyu(JSONObject jsonObject) {
        return "<!DOCTYPE html>" +
                "<html lang=\"zh-CN\">" +
                "<head>" +
                "<meta charset=\"UTF-8\">" +
                "<meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge,chrome=1\"/>" +
                "<meta name=\"format-detection\" content=\"telephone=no\">" +
                "<meta name=\"msapplication-tap-highlight\" content=\"no\">" +
                "<meta name=\"viewport\"" +
                "content=\"user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width\">" +
                "<title>四川省总工会</title>" +
                "<link rel=\"stylesheet\" href=\"zixun.min.css\">" +
                "</head>" +
                "<body style=\"padding: 5px; background-color:#fff\">" +
                JsonUtil.getString(jsonObject, "content") +
                "</body>" +
                "</html>";
    }

    /**
     * Date
     *
     * @return
     */
    public static Date DateStringe(String date, SimpleDateFormat df) {
        try {
            Date strDate = df.parse(date);
            return strDate;
        } catch (Exception ex) {
            System.out.println(ex.getMessage());
        }
        return null;
    }


    public static void tis(List<String> permissions, Context context) {
        for (String s : permissions) {
            if (s.equals(Manifest.permission.ACCESS_FINE_LOCATION)) {
                ToastUtils.showToast(context, "为了更好的为您提供对应服务，请到手机设置或权限管理中，开启地理位置权限");
                return;
            } else if (s.equals(Manifest.permission.READ_PHONE_STATE)) {
                ToastUtils.showToast(context, "为了更好的为您提供对应服务，请到手机设置或权限管理中，开启允许读取手机状态的权限");
                return;
            } else if (s.equals(Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
                ToastUtils.showToast(context, "为了更好的为您提供对应服务，请到手机设置或权限管理中，开启存储读取权限");
                return;
            } else if (s.equals(Manifest.permission.CAMERA)) {
                ToastUtils.showToast(context, "为了更好的为您提供对应服务，请到手机设置或权限管理中，开启摄像头权限");
                return;
            }
        }
    }

    public static void callHelpDeilsActivity(String url, Context c, String method) {
        Intent intent = new Intent();
        intent.setClass(c, WebViewDetailedActivity.class);
        Bundle bundle = new Bundle();
        bundle.putString("url", url);
        bundle.putString("method", method);
        bundle.putBoolean("type", true);
        intent.putExtras(bundle);
        c.startActivity(intent);
    }

    public static void callHelpDeilsActivity(Context c, Bundle bundle) {
        Intent intent = new Intent();
        intent.setClass(c, WebViewDetailedActivity.class);
        bundle.putBoolean("type", true);
        intent.putExtras(bundle);
        c.startActivity(intent);
    }

    public static void callNoTitle(String url, Context c, String method) {
        Intent intent = new Intent();
        intent.setClass(c, WebViewNoTitleActivity.class);
        Bundle bundle = new Bundle();
        bundle.putString("method", method);
        bundle.putString("url", url);
        intent.putExtras(bundle);
        c.startActivity(intent);
    }

    public static void setIndicator(TabLayout tabs, int leftDip, int rightDip) {
        Class<?> tabLayout = tabs.getClass();
        Field tabStrip = null;
        try {
            tabStrip = tabLayout.getDeclaredField("mTabStrip");
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        }

        tabStrip.setAccessible(true);
        LinearLayout llTab = null;
        try {
            llTab = (LinearLayout) tabStrip.get(tabs);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }
        int left = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, leftDip, Resources.getSystem().getDisplayMetrics());
        int right = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, rightDip, Resources.getSystem().getDisplayMetrics());
        for (int i = 0; i < llTab.getChildCount(); i++) {
            View child = llTab.getChildAt(i);
            child.setPadding(0, 0, 0, 0);
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(0, LinearLayout.LayoutParams.MATCH_PARENT, 1);
            params.leftMargin = left;
            params.rightMargin = right;
            child.setLayoutParams(params);
            child.invalidate();
        }
    }

}
